package org.szgb.console.zx.task.web;

import cn.hutool.http.HttpStatus;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.szgb.console.sys.file.entity.SysFile;
import org.szgb.console.sys.file.service.SysFileService;
import org.szgb.console.sys.user.entity.SysUser;
import org.szgb.console.sys.user.service.SysUserService;
import org.szgb.console.utils.PageView;
import org.szgb.console.utils.TokenUtil;
import org.szgb.console.zx.task.entity.ZxTask;
import org.szgb.console.zx.task.entity.ZxTaskForm;
import org.szgb.console.zx.task.service.ZxTaskFormService;
import org.szgb.console.zx.task.service.ZxTaskService;
import org.szgb.core.base.entity.ApprovalDto;
import org.szgb.core.base.entity.GetIdDto;
import org.szgb.core.utils.AjaxJson;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping(value = "/zx/task")
@Tag(name = "专项任务管理", description = "专项任务管理模块")
public class ZxTaskController {
    private final ZxTaskService zxTaskService;
    private final SysUserService sysUserService;
    private final ZxTaskFormService zxTaskFormService;
    private final SysFileService sysFileService;

    @Autowired
    public ZxTaskController(ZxTaskService zxTaskService, SysUserService sysUserService, ZxTaskFormService zxTaskFormService, SysFileService sysFileService) {
        this.zxTaskService = zxTaskService;
        this.sysUserService = sysUserService;
        this.zxTaskFormService = zxTaskFormService;
        this.sysFileService = sysFileService;
    }


    @Operation(summary = "获取专项任务信息", description = "根据查询参数获取专项任务信息，支持分页查询。使用id获取更详细的信息。")
    @PostMapping("/get")
    public AjaxJson get(@RequestBody(required = false) ZxTask.ZxTaskFindDto findDto, HttpServletRequest request, HttpServletResponse response) {
        // 创建一个PageView对象，用于分页显示
        if (findDto == null) {
            findDto = new ZxTask.ZxTaskFindDto();
        }
        PageView<ZxTask.ZxTaskListView> pageView = new PageView<>();
        ZxTask zxTask = findDto.toZxTask();
        // 如果实体对象的ID不为空，则直接调用get方法获取单个实体对象
        if (zxTask != null && zxTask.getId() != null && !zxTask.getId().isEmpty()) {
            ZxTask task = zxTaskService.get(zxTask.getId());
            // 如果实体对象为空，则返回错误响应
            if (task == null) {
                return AjaxJson.error("数据不存在", HttpStatus.HTTP_NOT_FOUND, request, response);
            }
            if (task.getMemberIds() == null) {
                task.setMemberIds("");
            }
            // 返回成功的响应，并将实体对象放入响应中
            return AjaxJson.success(request, response).put("zxTask", task.toZxTaskView(sysUserService.getByIdList(task.getMemberIds().split(",")).stream().map(SysUser::getName).collect(Collectors.joining(","))));
        } else {
            // 设置Page对象的列表属性，包含根据实体对象查询到的数据
            pageView.setList(ZxTask.ZxTaskListView.getListViewListFromList(zxTaskService.findList(zxTask)));
            // 设置Page对象的总记录数属性，用于分页显示
            pageView.setCount(zxTaskService.getCount(zxTask));
            // 创建一个成功的AjaxJson对象，并放入Page对象，以便于前端展示
            return AjaxJson.success(request, response).put("page", pageView);
        }
    }

    @Operation(summary = "获取专项任务表单", description = "获取专项任务表单,id必填")
    @PostMapping("/getForm")
    public AjaxJson getForm(@RequestBody GetIdDto idDto, HttpServletRequest request, HttpServletResponse response) {
        ZxTask zxTask = zxTaskService.get(idDto.getId());
        ZxTaskForm zxTaskForm = new ZxTaskForm();
        zxTaskForm.setTask(new ZxTask(idDto.getId()));
        // 获取表单项
        List<ZxTaskForm> zxTaskFormList = zxTaskFormService.findList(zxTaskForm);
        List<ZxTaskForm.ZxTaskFormItemView> formItemViewList = ZxTaskForm.ZxTaskFormItemView.getViewListFromList(zxTaskFormList);
        // 获取任务文件
        List<SysFile.SysFileView> fileViewList = null;
        if (zxTask.getZxPlan().getTaskFileIds() != null && !zxTask.getZxPlan().getTaskFileIds().isEmpty()) {
            List<SysFile> taskFileList = sysFileService.getByIdArray(zxTask.getZxPlan().getTaskFileIds().split(","));
            fileViewList = SysFile.SysFileView.getViewListFromList(taskFileList);
        }
        ZxTask.ZxTaskTableView zxTaskTableView = new ZxTask.ZxTaskTableView(zxTask, formItemViewList, fileViewList);
        return AjaxJson.success(request, response).put("zxTaskTableView", zxTaskTableView);
    }


    @PostMapping("/save")
    @Operation(summary = "保存专项任务", description = "新增或更改专项任务信息。")
    public AjaxJson save(@RequestBody ZxTask.ZxTaskSaveDto zxTaskSaveDto, HttpServletRequest request, HttpServletResponse response) {
        if (zxTaskSaveDto == null) {
            return AjaxJson.error("参数错误", HttpStatus.HTTP_BAD_REQUEST, request, response);
        }
        ZxTask zxTask = zxTaskSaveDto.toZxTask();
        // 设置实体对象的更新者为当前用户
        zxTask.setUpdatedBy(new SysUser(TokenUtil.getUid(request)));
        // 调用服务层的save方法，尝试保存或更新实体对象，返回保存结果的Map
        zxTaskService.save(zxTask);
        // 根据保存结果返回相应的AjaxJson对象
        return AjaxJson.success("保存成功", request, response).put("zxTask", zxTask.toZxTaskView(sysUserService.getByIdList(zxTask.getMemberIds().split(",")).stream().map(SysUser::getName).collect(Collectors.joining(","))));
    }

    @PostMapping("/assign")
    @Operation(summary = "派发任务", description = "综合员派发任务")
    public AjaxJson assign(@RequestBody ZxTask.ZxTaskAssignDto zxTaskAssignDto, HttpServletRequest request, HttpServletResponse response) throws IOException, InterruptedException {
        ZxTask zxTask = zxTaskAssignDto.toZxTask();
        // 设置实体对象的更新者为当前用户
        zxTask.setUpdatedBy(new SysUser(TokenUtil.getUid(request)));
        zxTaskService.assign(zxTask);
        // 根据保存结果返回相应的AjaxJson对象
        return AjaxJson.success("保存成功", request, response);
    }

    @PostMapping("/reAssign")
    @Operation(summary = "重新派发任务", description = "综合员重新派发任务")
    public AjaxJson reAssign(@RequestBody ZxTask.ZxTaskAssignDto zxTaskAssignDto, HttpServletRequest request, HttpServletResponse response) throws IOException, InterruptedException {
        ZxTask zxTask = zxTaskAssignDto.toZxTask();
        // 设置实体对象的更新者为当前用户
        zxTask.setUpdatedBy(new SysUser(TokenUtil.getUid(request)));
        zxTaskService.reAssign(zxTask);
        // 根据保存结果返回相应的AjaxJson对象
        return AjaxJson.success("保存成功", request, response);
    }

    @PostMapping("/submitForm")
    @Operation(summary = "提交专项任务表单", description = "提交专项任务表单")
    public AjaxJson submitForm(@RequestBody ZxTask.ZxTaskSubmitDto zxTaskSubmitDto, HttpServletRequest request, HttpServletResponse response) throws IOException, InterruptedException {
        // 获取已填写表单列表
        List<ZxTaskForm> zxTaskFormList = zxTaskSubmitDto.getZxTaskFormSubmitDtoList().stream().filter(zxTaskFormSubmitDto -> zxTaskFormSubmitDto.getIsFinish() == true).map(ZxTaskForm.ZxTaskFormSubmitDto::toZxTaskForm).toList();
        ZxTask zxTask = zxTaskService.get(zxTaskSubmitDto.getId());
        // 设置实体对象的更新者为当前用户
        zxTask.setUpdatedBy(new SysUser(TokenUtil.getUid(request)));
        zxTaskService.submitForm(zxTaskFormList, zxTask);

        return AjaxJson.success(request, response);
    }

    @PostMapping("/leaderApproval")
    @Operation(summary = "牵头人审批", description = "牵头人审批。")
    public AjaxJson leaderApproval(@RequestBody ApprovalDto approvalDto, HttpServletRequest request, HttpServletResponse response) throws IOException, InterruptedException {
        // 处理待办
        zxTaskService.leaderApproval(approvalDto, new SysUser(TokenUtil.getUid(request)));
        return AjaxJson.success(request, response);
    }

    @PostMapping("/leaderApprovalReturn")
    @Operation(summary = "牵头人快速退回", description = "牵头人快速退回。")
    public AjaxJson leaderApprovalReturn(@RequestBody GetIdDto idDto, HttpServletRequest request, HttpServletResponse response) throws IOException, InterruptedException {
        // 处理待办
        zxTaskService.leaderApprovalReturn(idDto.getId());
        return AjaxJson.success(request, response);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除专项任务", description = "根据ID删除专项任务信息。", parameters = {@Parameter(name = "ids", description = "专项任务ID列表，多个ID用英文逗号分隔。")})
    public AjaxJson delete(@RequestParam String ids, HttpServletRequest request, HttpServletResponse response) {
        // 检查ID参数是否为空，为空则返回错误响应
        if (ids == null) {
            return AjaxJson.error("参数错误", HttpStatus.HTTP_BAD_REQUEST, request, response);
        }
        // 调用服务层方法，执行删除操作
        zxTaskService.delete(ids);
        // 返回成功响应
        return AjaxJson.success(request, response);
    }
}
